import ViewManager from '../view/ViewManager';
import DataModel from '../model/DataModel';
import {Constant} from '../Constant';
import {CommonUtils} from './CommonUtils';
import { AppElementInfo } from '../../bean/AppElementInfo';
import { ElementUtils } from '../utils/ElementUtils';

(function(PLUGIN_ID) {
  'use strict';

  const message = {
    'en': {
      query_area_title: 'Set Filter Condition for Data',
      mapping_result: 'Mapping Result',
      tab_setting: 'Settings',
      tab_graph: '&nbsp Graph &nbsp',
      show_graph: 'ShowGraph',
      save_status: 'Save Status',
      permission_error: 'Your Permission is Not Enough,Please Contact the Administrator!'
    },
    'zh': {
      query_area_title: '数据筛选条件设定',
      mapping_result: '映射结果',
      tab_setting: '设置',
      tab_graph: '图表',
      show_graph: '显示图表',
      save_status: '状态保存',
      permission_error: '您的权限不足，请联系管理员！'
    },
    'ja': {
      query_area_title: 'データ絞り込み条件設定',
      mapping_result: 'マッピング結果',
      tab_setting: 'セットアップ',
      tab_graph: 'チャート',
      show_graph: 'グラフを表示',
      save_status: '状態保存する',
      permission_error: 'あなたは閲覧権ありません、管理者に連絡してください!'
    }
  };
  const lang = kintone.getLoginUser().language;
  const i18n = (lang in message) ? message[lang] : message['zh'];
  let config;
  const validateConfig = () => {
    config = kintone.plugin.app.getConfig(PLUGIN_ID);
    return config !== null;
  };
  if (!validateConfig()) {
    return;
  }
  const APP_SPACE_ID = config.spaceId;
  let needsReload = false;
  let viewManager;
  let dataModel;
  let configInfo;
  const tableElementsModels = [];
  kintone.events.on('app.record.detail.show', (event) => {
    if (needsReload) {
      needsReload = false;
      window.location.reload();
    }
    const record = event.record;
    kintone.app.record.setFieldShown(`${config[`${Constant.CONFIG_FIRST_APP_ID}`]}`, false);
    kintone.app.record.setFieldShown(`${config[`${Constant.CONFIG_SECOND_APP_ID}`]}`, false);
    kintone.app.record.setFieldShown(`${config[`${Constant.CONFIG_CONFIG_INFO_ID}`]}`, false);
    dataModel = new DataModel(config);
    viewManager = new ViewManager(APP_SPACE_ID, i18n);
    viewManager.initTabView(Constant.SETTING_AREA_ID, Constant.RESULT_LIST_AREA_ID, Constant.QUERYS_AREA_ID);
    viewManager.setOnclickSaveStatusEvent(saveConfigInfo);
    $('#tab_view').tabs({
      activate: function(e, ui) {
        const index = ui.newTab.index();
        if (index === 0 && tableElementsModels.length > 1) {
          tableElementsModels.forEach(tableElementsModel =>{
            viewManager.showPointsByElementIds(tableElementsModel.getTableElementIds());
          });
        } else if (tableElementsModels.length > 1) {
          tableElementsModels.forEach(tableElementsModel =>{
            viewManager.hidePointsByElementIds(tableElementsModel.getTableElementIds());
          });
        }
      }
    });

    const configInfoString = record[`${config[`${Constant.CONFIG_CONFIG_INFO_ID}`]}`].value;
    if (configInfoString !== '') {
      configInfo = JSON.parse(configInfoString);
    }
    // get app fields
    const appRequests = dataModel.getAppElementInfos(record);
    Promise.all(appRequests).then(appElementInfo =>{
      
    }).catch(error =>{
      alert(error.message);
    });
    if (appRequests.length > 1) {
      initJsPlumbEvent();
    }
  });
  kintone.events.on('app.record.edit.show', (event)=>{
    needsReload = true;
    event.record.configInfo.disabled = true;
    return event;
  });
  kintone.events.on('app.record.create.show', (event)=>{
    event.record.configInfo.disabled = true;
    return event;
  });
  function saveConfigInfo() {
    const queryDatas = [];
    tableElementsModels.forEach(tableElementsModel =>{
      queryDatas.push(tableElementsModel.query);
    });
    configInfo[Constant.QUERY_DATAS] = queryDatas;
    dataModel.saveConfigInfo(config, kintone.app.getId())
      .then((response) =>{
        alert('save success!');
      }).catch((error) =>{
        alert(error.message);
      });
  }
  function initJsPlumbEvent() {
    jsPlumb.bind('connection', (info) => {
      checkIsNeedShowTableButton();
      connectPoint(info.sourceId, info.targetId);
    });
    jsPlumb.bind('connectionDetached', (info) => {
      deleteElementFromContactDataList(CommonUtils.generateContactId(info.sourceId, info.targetId));
    });
    jsPlumb.bind('dblclick', (conn) =>{
      deleteElementFromContactDataList(CommonUtils.generateContactId(conn.sourceId, conn.targetId));
      jsPlumb.deleteConnection(conn);
    });
  }
  function deleteElementFromContactDataList(elementId) {
    console.log(`deleteId_${elementId}`);
    delete (contactElements.elements)[elementId];
    // delete element in configInfo[contactConfigs]
    if (configInfo.contactConfigs !== undefined && configInfo.contactConfigs[elementId] !== undefined) {
      delete (configInfo.contactConfigs)[elementId];
    }
    console.log(configInfo);
    if (!document.getElementById(elementId)) {
      return;
    }
    const element = document.getElementById(elementId);
    console.log(element);
    _elementView.contact_element_list.removeChild(element);
    const bt_container = document.getElementById(Constant.SHOW_ANALYZE_BT_ID);
    if (contactElements.elementsValue.length === 0 && bt_container) {
      // _elementView.diagramHorizonalContainer.removeChild(bt_container);
      _elementView.diagramHorizonalContainer.removeChild(bt_container);
    }
  }
  function checkIsNeedShowTableButton() {
    if (contactElements.elementsValue.length === 0) {
      const showTable = ElementUtils.generateShowGraphButton(i18n.show_graph);
      showTable.addEventListener('click', showAnalyzeTable);
      _elementView.diagramHorizonalContainer.appendChild(showTable);
    }
  }
  function connectPoint(sourceId, targetId) {
    const elementId = CommonUtils.generateContactId(sourceId, targetId);
    console.log(configInfo);

    console.log(contactElements.elements);
    // delete repeat line
    if (contactElements.elements.hasOwnProperty(elementId)) {
      return;
    }
    const contactKeys = Object.keys(contactElements.elements);
    console.log(contactKeys);
    contactKeys.forEach(contactKey =>{
      console.log(contactKey);
      const originalIds = contactKey.split('|');
      if (sourceId === originalIds[0] || targetId === originalIds[1]) {
        deleteFromContactDataList(contactKey);
      }
    });

    const contactElement = initContactElement(elementId, new TableAttribute(CommonUtils.generateContactText(sourceId, targetId)));
    contactElement.dataSource.sourceId = sourceId;
    contactElement.dataSource.targetId = targetId;
    contactElement.isCustomElement = originalData[sourceId].isCustomElement || originalData[targetId].isCustomElement;
    _elementView.contact_element_list.appendChild(contactElement.elementView);
    console.log('contactElements');
    contactElements.addElement(contactElement);
    console.log(contactElements);
    // if configConfigs[elementId] has value set it into contactELement labelName
    const contactConfigs = configInfo.contactConfigs;
    console.log(contactConfigs);
    if (contactConfigs !== undefined && contactConfigs[elementId] !== undefined && contactConfigs[elementId].contactLabelName !== undefined
      && contactConfigs[elementId].contactLabelName !== '') {
      const labelName = contactConfigs[elementId].contactLabelName;
      contactElements.elements[elementId].tableAttribute.labelName = labelName;
      document.getElementById(elementId).children[0].children[0].value = labelName;
    } else {
      configInfo.contactConfigs[elementId] = new ContactConfigInfo([sourceId, targetId]);
    }
  }
})(kintone.$PLUGIN_ID);